include('shared.lua');

PANEL = {};
ENTITY = nil;
BUFFER = 0;
function PANEL:Init()
	self.VGUI = {
		BT_OnOff = vgui.Create("DButton",self);
		BT_Overload = vgui.Create("DButton",self);
		Text = {"N/A","N/A","N/A"};
	};
	
	self:SetSize(210,100);
	self:Center();
	
	self.VGUI.BT_OnOff:SetText("Off");
	self.VGUI.BT_OnOff:SetPos(135,35);
	self.VGUI.BT_OnOff.State = false;
	self.VGUI.BT_OnOff.Delay = 2.7;
	self.VGUI.BT_OnOff.Next = CurTime();
	self.VGUI.BT_OnOff.DoClick = 
		function()
			if (self.VGUI.BT_OnOff.Next > CurTime()) then return end;
			if (self.VGUI.BT_OnOff.State) then
				self.VGUI.BT_OnOff:SetText("Off");
				LocalPlayer():ConCommand("TurnOff");
			else
				self.VGUI.BT_OnOff:SetText("On");
				LocalPlayer():ConCommand("TurnOn");
			end
			self.VGUI.BT_OnOff.State = not self.VGUI.BT_OnOff.State;
			self.VGUI.BT_OnOff.Next = CurTime() + self.VGUI.BT_OnOff.Delay;
		end
		
	self.VGUI.BT_Overload:SetText("Overload");
	self.VGUI.BT_Overload:SetPos(135,60);
	self.VGUI.BT_Overload.State = false;
	self.VGUI.BT_Overload.DoClick =
		function()
			LocalPlayer():ConCommand("Overload");
		end
end

function PANEL:PerformLayout()
	local w,h = self:GetSize();
	self.VGUI.BT_OnOff:SetPos(w-75,35);
	self.VGUI.BT_Overload:SetPos(w-75,60);
end

function PANEL:Paint()
	draw.RoundedBox(10,0,0,self:GetWide(),self:GetTall(),Color(16,16,16,255));
	draw.DrawText("ZPM Device","ScoreboardText",30,8,Color(255,255,255,255),0);
	draw.DrawText(self.VGUI.Text[1],"ScoreboardText",10,30,Color(255,255,255,255),0);
	draw.DrawText(self.VGUI.Text[2],"ScoreboardText",10,45,Color(255,255,255,255),0);
	draw.DrawText(self.VGUI.Text[3],"ScoreboardText",10,60,Color(255,255,255,255),0);
	draw.DrawText("Overload: "..tostring(BUFFER).."%","ScoreboardText",10,75,Color(255,255,255,255),0);
	return true;
end

function PANEL:Think()
	if (not Window or not Window:IsVisible()) then return end;
end

function PANEL:SetEntity(e)
	ENTITY = e;
end

function PANEL:Update(e,o,z,b)
	if (ENTITY == e) then
		for i=1,3 do
			if (z[i] == -1) then
				self.VGUI.Text[i] = "N/A";
			else
				if (o) then
					self.VGUI.Text[i] = "Connected: "..tostring(z[i]).."%";
				else
					self.VGUI.Text[i] = "Disconnected...";
				end
			end
		end
		
		BUFFER = b;
	end
end

vgui.Register("ZPD_ControlPanel",PANEL,"Frame");

usermessage.Hook("ZPD_Update",
	function(data)
		local e = data:ReadEntity();
		local o = data:ReadBool();
		local z = {};
		z[1] = data:ReadShort();
		z[2] = data:ReadShort();
		z[3] = data:ReadShort()
		local b = data:ReadShort();
		if (not Window) then Window = vgui.Create("ZPD_ControlPanel") end;
		Window:Update(e,o,z,b);
	end
);

usermessage.Hook("Show_ZPD_Console",
	function(data)
		local e = data:ReadEntity();
		if (ValidEntity(e)) then
			if (not Window) then Window = vgui.Create("ZPD_ControlPanel") end;
			Window:SetVisible(true);
			Window:SetEntity(e);
		end
	end
);